用循环队列输出直角杨辉三角

思想:杨辉三角的第n行的第i个数字等于第n-1行的第i-1个数字和第i个数字的和(其中i不等于1,不等于n)

/*用循环队列解决输出杨辉三角的问题*/
#include <stdio.h>
#include <malloc.h>
#define MAXSIZE 50

typedef int ElementType;
struct Queue//声明结构体 
{
	ElementType data[MAXSIZE];
	int front;//循环队列和顺序栈中使用整型值来表示首尾 
	int rear;//队尾指针指向队尾元素的下一单元 
};
int InitQueue(Queue *Q)//对队列进行初始化
{
		Q->rear=Q->front=0;
} 
int IsEmpty(Queue* Q)
{
	if(Q->front==Q->rear) return true;
	else return false;
}
int IsFull(Queue* Q)
{
	if(Q->front==(Q->rear+1)%MAXSIZE) return true;
	else return false; 
}
int EnterQueue(Queue* Q,ElementType x)
{
	if(IsFull(Q)==false)
	{
	    Q->data[Q->rear]=x;
     	Q->rear=(Q->rear+1)%MAXSIZE;
     	return true;
	}
	else
	{
		return false;
	}
}
int DeleteQueue(Queue *Q,ElementType *x)
{
	if(IsEmpty(Q)==false)
	{
		*x=Q->data[Q->front];
		Q->front=(Q->front+1)%MAXSIZE;
		return true;
	}
	else
	{
		return false;
	}
}
int GetHead(Queue *Q,ElementType *x)
{
	if(IsEmpty(Q)==true) return false;
	else 
	{
		*x=Q->data[Q->front];
		return true;
	}
}
void ClearQueue(Queue *Q)
{
	Q->rear=Q->front=0;
	
}
void DestroyQueue(Queue *Q)
{
	free(Q->data);//销毁队列,将结构体的数组销毁,数组名即是地址 
}
int main()
{
	void YangHuiTriangle(int n);
	int N=20;
	YangHuiTriangle(N);
	return 0;
}
void YangHuiTriangle(int N)
{
	ElementType *x=(ElementType *)malloc(sizeof(ElementType)); 
	ElementType *temp=(ElementType *)malloc(sizeof(ElementType)); 
	Queue *Q=(Queue *)malloc(sizeof(Queue));
	InitQueue(Q);
	EnterQueue(Q,1);
	for(int n=2;n<=N;n++)
	{
		EnterQueue(Q,1);
		for(int i=1;i<=n-2;i++)
		{
			DeleteQueue(Q,temp);
			printf("%d ",*temp);
			GetHead(Q,x);
			*temp=*temp+*x;
			EnterQueue(Q,*temp);
		}
		DeleteQueue(Q,x);
		printf("%d \n",*x);
		EnterQueue(Q,1);
	}
    
} 


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值